﻿// ------------------------------------------------------------------------
//    YATSE - A touch screen remote controller for XBMC (.NET 3.5)
//    Copyright (C) 2010  Tolriq (http://code.google.com/p/yatse/)
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
// ------------------------------------------------------------------------

using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Forms;
using XBMC;
using YATSE.Libs;
using Application = System.Windows.Forms.Application;
using ListBox = System.Windows.Controls.ListBox;
using MessageBox = System.Windows.Forms.MessageBox;
using MouseEventArgs = System.Windows.Input.MouseEventArgs;

namespace YATSE
{
    public partial class YatseWindow
    {

        private void btn_Video_Click(object sender, RoutedEventArgs e)
        {
            ShowGrid(grd_Video);
        }

        private void btn_Music_Click(object sender, RoutedEventArgs e)
        {
            ShowGrid(grd_Music);
        }

        private void btn_Current_Click(object sender, RoutedEventArgs e)
        {
            ShowGrid(grd_Current);
        }

        private void btn_Remote_Click(object sender, RoutedEventArgs e)
        {
            ShowGrid(grd_Remote);
        }

        private void btn_Settings_XBMCTest_Click(object sender, RoutedEventArgs e)
        {
            ResetTimer();
            var xbmc = new XbmcCommunicator();
            if (txt_Settings_XBMCIp.Text == "")
            {
                MessageBox.Show(_lang.GetString("1","Please configure first !"));
                return;
            }
            xbmc.SetCredentials(txt_Settings_XBMCLogin.Text, txt_Settings_XBMCPassword.Text);
            xbmc.SetIp(txt_Settings_XBMCIp.Text + ":" + txt_Settings_XBMCPort.Text);
            var res = xbmc.SetResponseFormat();
            MessageBox.Show(res
                                ? _lang.GetString("2","XBMC parameters are OK")
                                : _lang.GetString("3","Bad XBMC parameters\nPlease check :\n- XBMC is running\n- Web Server is enabled"));
        }

        private void btn_Settings_SelectImagesDirectory_Click(object sender, RoutedEventArgs e)
        {
            ResetTimer();
            var dialog = new FolderBrowserDialog
                             {
                                 SelectedPath = txt_Settings_ImagesDirectory.Text
                             };
            var result = dialog.ShowDialog();

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                txt_Settings_ImagesDirectory.Text = dialog.SelectedPath;
            }
        }

        private void btn_Settings_SaveSettings_Click(object sender, RoutedEventArgs e)
        {
            ResetTimer();
            _config.IsConfigured = true;
            if (chk_Settings_SecondScreen.IsChecked != null)
                _config.SecondScreen = (bool)chk_Settings_SecondScreen.IsChecked;
            if (chk_Settings_Topmost.IsChecked != null)
                _config.TopMost = (bool)chk_Settings_Topmost.IsChecked;
            if (chk_Settings_KeepFocus.IsChecked != null)
                _config.KeepFocus = (bool)chk_Settings_KeepFocus.IsChecked;
            if (chk_Settings_ForceResolution.IsChecked != null)
                _config.ForceResolution = (bool)chk_Settings_ForceResolution.IsChecked;
            if (chk_Settings_Diaporama.IsChecked != null)
                _config.Diaporama = (bool)chk_Settings_Diaporama.IsChecked;
            if (chk_Settings_Dimming.IsChecked != null)
                _config.Dimming = (bool)chk_Settings_Dimming.IsChecked;
            if (chk_Settings_Currently.IsChecked != null)
                _config.Currently = (bool)chk_Settings_Currently.IsChecked;
            if (chk_Settings_CurrentlyMovie.IsChecked != null)
                _config.CurrentlyMovie = (bool)chk_Settings_CurrentlyMovie.IsChecked;
            if (chk_Settings_HideCursor.IsChecked != null)
                _config.HideCursor = (bool)chk_Settings_HideCursor.IsChecked;
            if (chk_Settings_ShowScrollBars.IsChecked != null)
                _config.ShowScrollBars = (bool)chk_Settings_ShowScrollBars.IsChecked;

            if (chk_Settings_UseBanner.IsChecked != null)
                _config.UseBanner = (bool)chk_Settings_UseBanner.IsChecked;
            if (chk_Settings_ShowOverlay.IsChecked != null)
                _config.ShowOverlay = (bool)chk_Settings_ShowOverlay.IsChecked;
            if (chk_Settings_ShowEmptyMusicGenre.IsChecked != null)
                _config.ShowEmptyMusicGenre = (bool)chk_Settings_ShowEmptyMusicGenre.IsChecked;
            if (chk_Settings_ManualRefresh.IsChecked != null)
                _config.ManualRefresh = (bool)chk_Settings_ManualRefresh.IsChecked;
            if (chk_Settings_DisableAnimations.IsChecked != null)
                _config.DisableAnimations = (bool)chk_Settings_DisableAnimations.IsChecked;
            _config.ImageDirectory = txt_Settings_ImagesDirectory.Text;
            _config.XBMCIp = txt_Settings_XBMCIp.Text;
            _config.XBMCLogin = txt_Settings_XBMCLogin.Text;
            _config.XBMCPassword = txt_Settings_XBMCPassword.Text;
            _config.XBMCPort = txt_Settings_XBMCPort.Text;
            _config.XBMCMac = txt_Settings_XBMCMac.Text;

            var resolution = (ScreenRes)lst_Settings_Resolution.SelectedItem;
            if (resolution != null)
            {
                _config.Resolution = resolution.Mode;
            }

            _config.Language = lst_Settings_Language.SelectedItem.ToString();
            _config.Skin = lst_Settings_Skin.SelectedItem.ToString();

            SaveConfig(_configFile);


            if (_config.HideCursor)
                Cursor = System.Windows.Input.Cursors.None;
            else
                Cursor = System.Windows.Input.Cursors.Arrow;


            Change_Display_Settings(null, null);

            InitXbmc();
            _isLibraryRefresh = false;
        }

        private void grd_Dimming_MouseDown(object sender, MouseButtonEventArgs e)
        {
            _isScreenSaver = false;
            ResetTimer();
            var stbDimmingHide = (Storyboard)TryFindResource("stb_HideDimming");
            stbDimmingHide.Begin(this);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Change_Display_Settings(sender, e);
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            WriteToLog("----- End YATSE -----");
        }

        private void grd_Diaporama_MouseDown(object sender, MouseButtonEventArgs e)
        {
            _isScreenSaver = false;
            ResetTimer();
            _diaporamaCurrentImage = 0;
            var stbDiaporamaHide = (Storyboard)TryFindResource("stb_HideDiaporama");
            stbDiaporamaHide.Begin(this);
        }

        private void prg_Progress_MouseDown(object sender, MouseButtonEventArgs e)
        {
            var mousePosition = e.GetPosition(prg_Current_Progress).X;
            var ratio = mousePosition / prg_Current_Progress.ActualWidth;
            var progressBarValue = ratio * prg_Current_Progress.Maximum;
            _xbmc.Controls.SeekPercentage((int)progressBarValue);
        }

        private void prg_Current_Progress_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton != MouseButtonState.Pressed) return;
            var mousePosition = e.GetPosition(prg_Current_Progress).X;
            var ratio = mousePosition / prg_Current_Progress.ActualWidth;
            var progressBarValue = ratio * prg_Current_Progress.Maximum;
            _xbmc.Controls.SeekPercentage((int)progressBarValue);
        }

        private void btn_Current_Previous_Click(object sender, RoutedEventArgs e)
        {
        	_xbmc.Controls.Previous();
        }

        private void btn_Current_Rewind_Click(object sender, RoutedEventArgs e)
        {
            var curPos = _xbmc.Status.GetProgress();
            curPos = Math.Max(1,curPos - 5);
            _xbmc.Controls.SeekPercentage(curPos);
        }

        private void btn_Current_Play_Click(object sender, RoutedEventArgs e)
        {
        	_xbmc.Controls.Play();
        }

        private void btn_Current_Pause_Click(object sender, RoutedEventArgs e)
        {
        	_xbmc.Controls.Play();
        }

        private void btn_Current_Stop_Click(object sender, RoutedEventArgs e)
        {
        	_xbmc.Controls.Stop();
        }

        private void btn_Current_Forward_Click(object sender, RoutedEventArgs e)
        {
            var curPos = _xbmc.Status.GetProgress();
            curPos = Math.Min(99, curPos + 5);
            _xbmc.Controls.SeekPercentage(curPos);
        }

        private void btn_Current_Next_Click(object sender, RoutedEventArgs e)
        {
        	_xbmc.Controls.Next();
        }

        private void btn_Current_VolDown_Click(object sender, RoutedEventArgs e)
        {
            var curVol= _xbmc.Status.GetVolume();
            curVol = Math.Max(0, curVol - 10);
            _xbmc.Controls.SetVolume(curVol);
            prg_Volume.Value = curVol;
            prg_Volume.Visibility = Visibility.Visible;
            btn_Volume_Mute.Visibility = Visibility.Hidden;
            ShowVolume();
        }

        private void btn_Current_VolMute_Click(object sender, RoutedEventArgs e)
        {
            var muted = ! _xbmc.Status.IsMuted();
        	_xbmc.Controls.ToggleMute();
            btn_Volume_Mute.Visibility = muted ? Visibility.Visible : Visibility.Hidden;
            ShowVolume(); 
        }

        private void btn_Current_VolUp_Click(object sender, RoutedEventArgs e)
        {
            var curVol = _xbmc.Status.GetVolume();
            curVol = Math.Min(100, curVol + 10);
            _xbmc.Controls.SetVolume(curVol);
            prg_Volume.Value = curVol;
            prg_Volume.Visibility = Visibility.Visible;
            btn_Volume_Mute.Visibility = Visibility.Hidden;
            ShowVolume();
        }

        private void btn_Remote_Return_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.SendAction("10");
        }

        private void btn_Remote_Info_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.SendAction("11");
        }

        private void btn_Remote_Up_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.SendAction("3");
        }

        private void btn_Remote_Left_Click(object sender, RoutedEventArgs e)
        {
        	_xbmc.Controls.SendAction("1");
        }

        private void btn_Remote_Enter_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.SendAction("7");
        }

        private void btn_Remote_Right_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.SendAction("2");
        }

        private void btn_Remote_Down_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.SendAction("4");
        }

        private void btn_Remote_Play_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.Play();
        }

        private void btn_Remote_Stop_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.Stop();
        }

        private void btn_Remote_Pause_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.Play();
        }

        private void btn_Remote_VolUp_Click(object sender, RoutedEventArgs e)
        {
            var curVol = _xbmc.Status.GetVolume();
            curVol = Math.Min(100, curVol + 10);
            _xbmc.Controls.SetVolume(curVol);
            prg_Volume.Value = curVol;
            prg_Volume.Visibility = Visibility.Visible;
            btn_Volume_Mute.Visibility = Visibility.Hidden;
            ShowVolume();
        }

        private void btn_Remote_VolDown_Click(object sender, RoutedEventArgs e)
        {
            var curVol = _xbmc.Status.GetVolume();
            curVol = Math.Max(0, curVol - 10);
            _xbmc.Controls.SetVolume(curVol);
            prg_Volume.Value = curVol;
            prg_Volume.Visibility = Visibility.Visible;
            btn_Volume_Mute.Visibility = Visibility.Hidden;
            ShowVolume();
        }

        private void btn_Remote_VolMute_Click(object sender, RoutedEventArgs e)
        {
            var muted = !_xbmc.Status.IsMuted();
            _xbmc.Controls.ToggleMute();
            btn_Volume_Mute.Visibility = muted ? Visibility.Visible : Visibility.Hidden;
            ShowVolume(); 
        }

        private void btn_Remote_Next_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.Next();
        }

        private void btn_Remote_Previous_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.Previous();
        }

        private void Window_MouseMove(object sender, MouseEventArgs e)
        {
            if (_currentGrid.Name == "grd_Music")
            {
                if (_isMouseDown)
                {
                    _mouseDownPoint = e.GetPosition(this);
                    _mouseDownTime = DateTime.Now;
                    var distanceX = _mouseDownPreviousPoint.X - _mouseDownPoint.X;
                    var timeX = _mouseDownTime.Subtract(_mouseDownPreviousTime).TotalMilliseconds;
                    if (timeX > 10)
                    {
                        var speed = distanceX/timeX;
                        var curIndex = lst_MusicGenre.SelectedIndex;
                        int newIndex;
                        if (speed > 0)
                            newIndex = (int)Math.Round(Math.Min(_genreDataSource.Count - 1, curIndex + speed * 2));
                        else
                            newIndex = (int)Math.Round(Math.Max(0, curIndex - Math.Abs(speed) * 2));
                        lst_MusicGenre.SelectedIndex = newIndex;
                        lst_MusicGenre.ScrollIntoView(lst_MusicGenre.Items[newIndex]);
                    }
                    _mouseDownPreviousPoint = _mouseDownPoint;
                    _mouseDownPreviousTime = _mouseDownTime;
                }
            }

            if (_currentGrid.Name == "grd_MusicAlbum")
            {
                if (_isMouseDown)
                {
                    _mouseDownPoint = e.GetPosition(this);
                    _mouseDownTime = DateTime.Now;
                    var distanceX = _mouseDownPreviousPoint.X - _mouseDownPoint.X;
                    var timeX = _mouseDownTime.Subtract(_mouseDownPreviousTime).TotalMilliseconds;
                    if (timeX > 10)
                    {
                        var speed = distanceX / timeX;
                        var curIndex = lst_Albums.SelectedIndex;
                        int newIndex;
                        if (speed > 0)
                            newIndex = (int)Math.Round(Math.Min(_albumDataSource.Count - 1, curIndex + speed * 2));
                        else
                            newIndex = (int)Math.Round(Math.Max(0, curIndex - Math.Abs(speed) * 2));
                        lst_Albums.SelectedIndex = newIndex;
                        if (lst_Albums.Items.Count >0 )
                            lst_Albums.ScrollIntoView(lst_Albums.Items[newIndex]);
                    }
                    _mouseDownPreviousPoint = _mouseDownPoint;
                    _mouseDownPreviousTime = _mouseDownTime;
                }
            }
        }

        private void Window_MouseUp(object sender, MouseButtonEventArgs e)
        {
            _isMouseDown = false;
            ResetTimer();
        }

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            ResetTimer();
            if (_currentGrid.Name == "grd_MusicAlbum")
            {
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    _isMouseDown = true;
                    _mouseDownPoint = e.GetPosition(this);
                    _mouseDownTime = DateTime.Now;
                    _mouseDownPreviousPoint = _mouseDownPoint;
                    _mouseDownPreviousTime = _mouseDownTime;
                    var now = DateTime.Now;
                    var dtime = now.Subtract(_mouseClickTime).TotalMilliseconds;
                    if (dtime < 300 && dtime > 30) // Double click
                    { 
                        if (lst_Albums.SelectedIndex >= 0)
                        {
                            var temp = (MusicAlbum)lst_Albums.Items.GetItemAt(lst_Albums.SelectedIndex);
                            _xbmc.Controls.PlayAlbum(temp.IdAlbum);
                        }
                    }
                    _mouseClickTime = _mouseDownTime;
                }
            }

            if (_currentGrid.Name == "grd_Music")
            {
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    _isMouseDown = true;
                    _mouseDownPoint = e.GetPosition(this);
                    _mouseDownTime = DateTime.Now;
                    _mouseDownPreviousPoint = _mouseDownPoint;
                    _mouseDownPreviousTime = _mouseDownTime;
                    var now = DateTime.Now;
                    var dtime = now.Subtract(_mouseClickTime).TotalMilliseconds;
                    if (dtime < 300 && dtime > 30) // Double click
                    { 
                        var temp = _genreDataSource.ElementAt(lst_MusicGenre.SelectedIndex);
                        _isMouseDown = false;
                        RefreshAlbums(temp.Id);
                        ShowGrid(grd_MusicAlbum);
                    }
                    _mouseClickTime = _mouseDownTime;
                }
            }
        }

        private void lst_Video_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ResetTimer();

            txt_Video_Title.Text = _lang.GetString("33", "No Medias");
            txt_Video_Tagline.Text = "";
            txt_Video_Year.Text = "";
            txt_Video_Director.Text = "";
            txt_Video_Genres.Text = "";

            if (lst_Video.SelectedItems.Count == 0) return;   
       
            var element = _filmDataSource.ElementAt(lst_Video.SelectedIndex);
            if (element == null) return;
            if (element.Fanart != null)
                if (File.Exists(element.Fanart))
                    img_Video_Fanart.Source = new BitmapImage(new Uri(element.Fanart));
            txt_Video_Title.Text = element.Title;
            txt_Video_Tagline.Text = element.Tagline;
            txt_Video_Year.Text = element.Year;
            txt_Video_Director.Text = element.Director;
            txt_Video_Genres.Text = element.Genre;
        }



        private void lst_Video_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var box = sender as ListBox;
            if (box != null)
            {
                var item = (ListBoxItem) GetObjectDataFromPoint(box, e.GetPosition(box)) ;
                if (item != null)
                {
                    if (!item.IsSelected)
                    {
                        var view = ItemsControl.ItemsControlFromItemContainer(item) as ListBox;
                        if (view != null)
                        {
                            var index = view.ItemContainerGenerator.IndexFromContainer(item);
                            _mouseClickItemNewIndex = _mouseClickItemIndex = index;
                        }
                    }
                }
                else
                {
                    e.Handled = false;
                    return;
                }
            }

            if (e.LeftButton == MouseButtonState.Pressed)
            {
                _isMouseDown = true;
                _mouseDownPoint = e.GetPosition(this);
                _mouseDownTime = DateTime.Now;
                _mouseDownPreviousPoint = _mouseDownPoint;
                _mouseDownPreviousTime = _mouseDownTime;
                var now = DateTime.Now;
                if (now.Subtract(_mouseClickTime).TotalMilliseconds < 250) // Double click
                { 
                    var temp = (Film)lst_Video.Items.GetItemAt(lst_Video.SelectedIndex);
                    _xbmc.Controls.PlayFile(temp.DirName+temp.FileName);
                }
                _mouseClickTime = _mouseDownTime;
            }

            e.Handled = true;
        }

        private void lst_Video_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (_isMouseDown)
            {
                _mouseDownPoint = e.GetPosition(this);
                _mouseDownTime = DateTime.Now;
                var distanceX = _mouseDownPreviousPoint.X - _mouseDownPoint.X;
                var timeX = _mouseDownTime.Subtract(_mouseDownPreviousTime).TotalMilliseconds;
                if (timeX > 10)
                {
                    var speed = distanceX / timeX;
                    var curIndex = _mouseClickItemIndex;
                    int newIndex;
                    if (speed > 0)
                        newIndex = (int)Math.Round(Math.Min(lst_Video.Items.Count - 1, curIndex + speed * 2));
                    else
                        newIndex = (int)Math.Round(Math.Max(0, curIndex - Math.Abs(speed) * 2));
                    if (newIndex >= 0)
                    {
                        lst_Video.ScrollIntoView(lst_Video.Items[newIndex]);
                        _mouseClickItemNewIndex = newIndex;
                    }

                }
                _mouseDownPreviousPoint = _mouseDownPoint;
                _mouseDownPreviousTime = _mouseDownTime;
            }
            e.Handled = false;
        }

        private void lst_Video_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            _isMouseDown = false;
            ResetTimer();
            var box = sender as ListBox;
            if (box != null)
            {
                var item = (ListBoxItem)GetObjectDataFromPoint(box, e.GetPosition(box));
                if (item != null)
                {
                    var view = ItemsControl.ItemsControlFromItemContainer(item) as ListBox;
                    var index = 0;
                    if (view != null)
                    {
                        index = view.ItemContainerGenerator.IndexFromContainer(item);
                    }
                    if (!item.IsSelected && _mouseClickItemIndex == index && _mouseClickItemIndex == _mouseClickItemNewIndex)
                    {
                        box.SelectedItems.Clear();
                        lst_Video.SelectedIndex = _mouseClickItemIndex;
                        lst_Video.ScrollIntoView(lst_Video.Items[_mouseClickItemIndex]);
                    }
                    /*else
                    {
                        box.SelectedItems.Clear();
                        lst_Video.SelectedIndex = _mouseClickItemNewIndex;
                    }*/
                }
            }
            e.Handled = false;
        }

        private void btn_Settings_ResfrehLibrary_Click(object sender, RoutedEventArgs e)
        {
            RefreshLibrary(true);
        }

        private void lst_Settings_Language_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (File.Exists(Application.StartupPath + @"\Langs\" + lst_Settings_Language.SelectedItem + ".xml"))
            {
                _lang.LoadXml(Application.StartupPath + @"\Langs\" + lst_Settings_Language.SelectedItem + ".xml");
            }
            LoadSkin();
        }

        private void btn_Remote_PlayCD_Click(object sender, RoutedEventArgs e)
        {
        	_xbmc.Controls.PlayDrive();
        }

        private void btn_Remote_Eject_Click(object sender, RoutedEventArgs e)
        {
        	_xbmc.Controls.EjectTray();
        }

        private void lst_Albums_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ResetTimer();
            txt_Album_Artist.Text = "";
            txt_Album_Genres.Text = "";
            txt_Album_Title.Text = _lang.GetString("33", "No Medias");
            txt_Album_Year.Text = "";
            if (lst_Albums.SelectedItems.Count == 0) return;

            var element = _albumDataSource.ElementAt(lst_Albums.SelectedIndex);
            if (element == null) return;

            txt_Album_Artist.Text = element.Artist;
            txt_Album_Genres.Text = element.Genre;
            txt_Album_Title.Text = element.Title;
            txt_Album_Year.Text = element.Year;
        }

        private void trp_Transition_TransitionCompleted(object sender, EventArgs e)
        {
        }

        private void btn_Actions_Click(object sender, RoutedEventArgs e)
        {
            ShowGrid(grd_Actions);
        }

        private void btn_TV_Click(object sender, RoutedEventArgs e)
        {
            ShowGrid(grd_TV);
        }

        private void btn_Actions_Close_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void btn_Actions_Settings_Click(object sender, RoutedEventArgs e)
        {
            if (_currentGrid == grd_Settings) return;
            chk_Settings_SecondScreen.IsChecked = _config.SecondScreen;
            chk_Settings_Topmost.IsChecked = _config.TopMost;
            chk_Settings_KeepFocus.IsChecked = _config.KeepFocus;

            chk_Settings_ForceResolution.IsChecked = _config.ForceResolution;
            chk_Settings_Diaporama.IsChecked = _config.Diaporama;
            chk_Settings_Dimming.IsChecked = _config.Dimming;
            chk_Settings_Currently.IsChecked = _config.Currently;
            chk_Settings_CurrentlyMovie.IsChecked = _config.CurrentlyMovie;
            chk_Settings_HideCursor.IsChecked = _config.HideCursor;

            chk_Settings_UseBanner.IsChecked = _config.UseBanner;
            chk_Settings_ShowOverlay.IsChecked = _config.ShowOverlay;
            chk_Settings_ShowEmptyMusicGenre.IsChecked = _config.ShowEmptyMusicGenre;

            chk_Settings_ManualRefresh.IsChecked = _config.ManualRefresh;
            chk_Settings_ShowScrollBars.IsChecked = _config.ShowScrollBars;
            chk_Settings_DisableAnimations.IsChecked = _config.DisableAnimations;

            txt_Settings_ImagesDirectory.Text = _config.ImageDirectory;
            txt_Settings_XBMCIp.Text = _config.XBMCIp;
            txt_Settings_XBMCLogin.Text = _config.XBMCLogin;
            txt_Settings_XBMCPassword.Text = _config.XBMCPassword;
            txt_Settings_XBMCPort.Text = _config.XBMCPort;
            txt_Settings_XBMCMac.Text = _config.XBMCMac;

            var screenRes = new ScreenResolution();
            var screens = Screen.AllScreens;
            var modes = screenRes.EnumModes(screens.Length == 1 ? 0 : 1);

            lst_Settings_Resolution.Items.Clear();
            foreach (var mode in modes.Where(mode => mode.dmBitsPerPel == 32 && mode.dmPelsWidth >= 800))
            {
                var index = lst_Settings_Resolution.Items.Add(new ScreenRes(mode));
                if (ScreenResolution.CompareDevMode(mode, _config.Resolution))
                {
                    lst_Settings_Resolution.SelectedIndex = index;
                }
            }

            lst_Settings_Skin.Items.Clear();
            var skins = Directory.GetDirectories(Application.StartupPath + @"\Skin");
            foreach (var skin in skins)
            {
                var skinname = skin.Replace(Application.StartupPath + @"\Skin\", "");
                var index = lst_Settings_Skin.Items.Add(skinname);
                if (skinname == _currentSkin)
                {
                    lst_Settings_Skin.SelectedIndex = index;
                }
            }

            lst_Settings_Language.Items.Clear();
            var langs = Directory.GetFiles(Application.StartupPath + @"\Langs", "*.xml");
            foreach (var lang in langs)
            {
                var langname = lang.Replace(Application.StartupPath + @"\Langs\", "").Replace(".xml", "");
                var index = lst_Settings_Language.Items.Add(langname);
                if (langname == _config.Language)
                {
                    lst_Settings_Language.SelectedIndex = index;
                }
            }

            ShowGrid(grd_Settings);
        }

        private void btn_Settings_GetMac_Click(object sender, RoutedEventArgs e)
        {
            var mac = NetworkTools.GetMACAddressFromARP(txt_Settings_XBMCIp.Text);
            txt_Settings_XBMCMac.Text = mac;
        }

        private void btn_Actions_Shutdown_Local_Click(object sender, RoutedEventArgs e)
        {
        	ShutdownOS();
        }

        private void btn_Actions_Reboot_Local_Click(object sender, RoutedEventArgs e)
        {
        	RebootOS();
        }

        private void btn_Actions_Shutdown_XBMC_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.Shutdown();
        }

        private void btn_Actions_WOL_XBMC_Click(object sender, RoutedEventArgs e)
        {
            var macAddress = Regex.Replace(_config.XBMCMac, @"[^0-9A-Fa-f]", "");
            NetworkTools.Wakeup(macAddress);
        }

        private void btn_Actions_Reboot_XBMC_Click(object sender, RoutedEventArgs e)
        {
        	_xbmc.Controls.Reboot();
        }

        private void lst_TvShow_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ResetTimer();

            txt_TvShow_Title.Text = _lang.GetString("33", "No Medias");
            txt_TvShow_Plot.Text = "";
            txt_TvShow_Year.Text = "";
            txt_TvShow_Studio.Text = "";
            txt_TvShow_Genres.Text = "";

            if (lst_TvShow.SelectedItems.Count == 0) return;

            var element = _showDataSource.ElementAt(lst_TvShow.SelectedIndex);
            if (element == null) return;
            if (element.Fanart != null)
                if (File.Exists(element.Fanart))
                    img_TvShow_Fanart.Source = new BitmapImage(new Uri(element.Fanart));
            txt_TvShow_Title.Text = element.Title;
            txt_TvShow_Plot.Text = element.Plot;
            txt_TvShow_Year.Text = element.Date;
            txt_TvShow_Studio.Text = element.Studio;
            txt_TvShow_Genres.Text = element.Genre;
        }



        private void lst_TvShow_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var box = sender as ListBox;
            if (box != null)
            {
                var item = (ListBoxItem)GetObjectDataFromPoint(box, e.GetPosition(box));
                if (item != null)
                {
                    if (!item.IsSelected)
                    {
                        var view = ItemsControl.ItemsControlFromItemContainer(item) as ListBox;
                        if (view != null)
                        {
                            var index = view.ItemContainerGenerator.IndexFromContainer(item);
                            _mouseClickItemNewIndex = _mouseClickItemIndex = index;
                        }
                    }
                }
                else
                {
                    e.Handled = false;
                    return;
                }
            }

            if (e.LeftButton == MouseButtonState.Pressed)
            {
                _isMouseDown = true;
                _mouseDownPoint = e.GetPosition(this);
                _mouseDownTime = DateTime.Now;
                _mouseDownPreviousPoint = _mouseDownPoint;
                _mouseDownPreviousTime = _mouseDownTime;
                var now = DateTime.Now;
                if (now.Subtract(_mouseClickTime).TotalMilliseconds < 250) // Double click
                {
                    var temp = (TvShow)lst_TvShow.Items.GetItemAt(lst_TvShow.SelectedIndex);
                    RefreshEpisodes(temp.IdShow);
                    ShowGrid(grd_TVEpisode);
                }
                _mouseClickTime = _mouseDownTime;
            }

            e.Handled = true;
        }

        private void lst_TvShow_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (_isMouseDown)
            {
                _mouseDownPoint = e.GetPosition(this);
                _mouseDownTime = DateTime.Now;
                var distanceX = _mouseDownPreviousPoint.X - _mouseDownPoint.X;
                var timeX = _mouseDownTime.Subtract(_mouseDownPreviousTime).TotalMilliseconds;
                if (timeX > 10)
                {
                    var speed = distanceX / timeX;
                    var curIndex = _mouseClickItemIndex;
                    int newIndex;
                    if (speed > 0)
                        newIndex = (int)Math.Round(Math.Min(lst_TvShow.Items.Count - 1, curIndex + speed * 2));
                    else
                        newIndex = (int)Math.Round(Math.Max(0, curIndex - Math.Abs(speed) * 2));
                    if (newIndex >= 0)
                    {
                        lst_TvShow.ScrollIntoView(lst_TvShow.Items[newIndex]);
                        _mouseClickItemNewIndex = newIndex;
                    }

                }
                _mouseDownPreviousPoint = _mouseDownPoint;
                _mouseDownPreviousTime = _mouseDownTime;
            }
            e.Handled = false;
        }

        private void lst_TvShow_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            _isMouseDown = false;
            ResetTimer();
            var box = sender as ListBox;
            if (box != null)
            {
                var item = (ListBoxItem)GetObjectDataFromPoint(box, e.GetPosition(box));
                if (item != null)
                {
                    var view = ItemsControl.ItemsControlFromItemContainer(item) as ListBox;
                    var index = 0;
                    if (view != null)
                    {
                        index = view.ItemContainerGenerator.IndexFromContainer(item);
                    }
                    if (!item.IsSelected && _mouseClickItemIndex == index && _mouseClickItemNewIndex == _mouseClickItemIndex)
                    {
                        box.SelectedItems.Clear();
                        lst_TvShow.SelectedIndex = _mouseClickItemIndex;
                        lst_TvShow.ScrollIntoView(lst_TvShow.Items[_mouseClickItemIndex]);
                    }
                    /*else
                    {
                        box.SelectedItems.Clear();
                        lst_Video.SelectedIndex = _mouseClickItemNewIndex;
                    }*/
                }
            }
            e.Handled = false;
        }

        private void lst_TvEpisode_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ResetTimer();

            txt_TvEpisode_Title.Text = _lang.GetString("33", "No Medias");
            txt_TvEpisode_Plot.Text = "";
            txt_TvEpisode_Year.Text = "";
            txt_TvEpisode_Studio.Text = "";
            txt_TvEpisode_Genres.Text = "";

            if (lst_TvEpisode.SelectedItems.Count == 0) return;

            var element = _episodeDataSource.ElementAt(lst_TvEpisode.SelectedIndex);
            if (element == null) return;
            if (element.Fanart != null)
                if (File.Exists(element.Fanart))
                    img_TvEpisode_Fanart.Source = new BitmapImage(new Uri(element.Fanart));
            txt_TvEpisode_Title.Text = element.Title;
            txt_TvEpisode_Plot.Text = element.Plot;
            txt_TvEpisode_Year.Text = element.Date;
            txt_TvEpisode_Studio.Text = "S" + element.Season + " / E" + element.Episode;
            txt_TvEpisode_Genres.Text = element.ShowTitle;
        }



        private void lst_TvEpisode_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var box = sender as ListBox;
            if (box != null)
            {
                var item = (ListBoxItem)GetObjectDataFromPoint(box, e.GetPosition(box));
                if (item != null)
                {
                    if (!item.IsSelected)
                    {
                        var view = ItemsControl.ItemsControlFromItemContainer(item) as ListBox;
                        if (view != null)
                        {
                            var index = view.ItemContainerGenerator.IndexFromContainer(item);
                            _mouseClickItemNewIndex = _mouseClickItemIndex = index;
                        }
                    }
                }
                else
                {
                    e.Handled = false;
                    return;
                }
            }

            if (e.LeftButton == MouseButtonState.Pressed)
            {
                _isMouseDown = true;
                _mouseDownPoint = e.GetPosition(this);
                _mouseDownTime = DateTime.Now;
                _mouseDownPreviousPoint = _mouseDownPoint;
                _mouseDownPreviousTime = _mouseDownTime;
                var now = DateTime.Now;
                if (now.Subtract(_mouseClickTime).TotalMilliseconds < 250) // Double click
                {
                    var temp = (TvEpisode)lst_TvEpisode.Items.GetItemAt(lst_TvEpisode.SelectedIndex);
                    _xbmc.Controls.PlayFile(temp.DirName + temp.FileName);
                }
                _mouseClickTime = _mouseDownTime;
            }

            e.Handled = true;
        }

        private void lst_TvEpisode_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (_isMouseDown)
            {
                _mouseDownPoint = e.GetPosition(this);
                _mouseDownTime = DateTime.Now;
                var distanceX = _mouseDownPreviousPoint.X - _mouseDownPoint.X;
                var timeX = _mouseDownTime.Subtract(_mouseDownPreviousTime).TotalMilliseconds;
                if (timeX > 10)
                {
                    var speed = distanceX / timeX;
                    var curIndex = _mouseClickItemIndex;
                    int newIndex;
                    if (speed > 0)
                        newIndex = (int)Math.Round(Math.Min(lst_TvEpisode.Items.Count - 1, curIndex + speed * 2));
                    else
                        newIndex = (int)Math.Round(Math.Max(0, curIndex - Math.Abs(speed) * 2));
                    if (newIndex >= 0)
                    {
                        lst_TvEpisode.ScrollIntoView(lst_TvEpisode.Items[newIndex]);
                        _mouseClickItemNewIndex = newIndex;
                    }

                }
                _mouseDownPreviousPoint = _mouseDownPoint;
                _mouseDownPreviousTime = _mouseDownTime;
            }
            e.Handled = false;
        }

        private void lst_TvEpisode_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            _isMouseDown = false;
            ResetTimer();
            var box = sender as ListBox;
            if (box != null)
            {
                var item = (ListBoxItem)GetObjectDataFromPoint(box, e.GetPosition(box));
                if (item != null)
                {
                    var view = ItemsControl.ItemsControlFromItemContainer(item) as ListBox;
                    var index = 0;
                    if (view != null)
                    {
                        index = view.ItemContainerGenerator.IndexFromContainer(item);
                    }
                    if (!item.IsSelected && _mouseClickItemIndex == index && _mouseClickItemNewIndex == _mouseClickItemIndex)
                    {
                        box.SelectedItems.Clear();
                        lst_TvEpisode.SelectedIndex = _mouseClickItemIndex;
                        lst_TvEpisode.ScrollIntoView(lst_TvEpisode.Items[_mouseClickItemIndex]);
                    }
                    /*else
                    {
                        box.SelectedItems.Clear();
                        lst_Video.SelectedIndex = _mouseClickItemNewIndex;
                    }*/
                }
            }
            e.Handled = false;
        }

        private void chk_Settings_CurrentlyMovie_Checked(object sender, RoutedEventArgs e)
        {
            if (chk_Settings_CurrentlyMovie.IsChecked == true)
                chk_Settings_Dimming.IsChecked = false;
        }

        private void chk_Settings_Dimming_Checked(object sender, RoutedEventArgs e)
        {
            if (chk_Settings_Dimming.IsChecked == true)
                chk_Settings_CurrentlyMovie.IsChecked = false;
        }

        private void btn_Remote_Key_A_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'A' : 'a';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_B_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'B' : 'b';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_C_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'C' : 'c';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_D_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'D' : 'd';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_E_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'E' : 'e';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_F_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'F' : 'f';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_G_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'G' : 'g';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_H_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'H' : 'h';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_I_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'I' : 'i';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_J_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'J' : 'j';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_K_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'K' : 'k';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_L_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'L' : 'l';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_M_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'M' : 'm';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_N_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'N' : 'n';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_O_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'O' : 'o';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_P_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'P' : 'p';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_Q_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'Q' : 'q';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_R_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'R' : 'r';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_S_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'S' : 's';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_T_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'T' : 't';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_U_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'U' : 'u';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_V_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'V' : 'v';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_W_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'W' : 'w';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_X_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'X' : 'x';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_Y_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'Y' : 'y';
            _xbmc.Controls.SendVirtKey(key);
        }
        private void btn_Remote_Key_Z_Click(object sender, RoutedEventArgs e)
        {
            var key = _keyShift ? 'Z' : 'z';
            _xbmc.Controls.SendVirtKey(key);
        }

        private void btn_Remote_Key_Caps_Click(object sender, RoutedEventArgs e)
        {
        	if (_keyShift)
        	{
                var imgCaps = new ImageBrush
                {
                    ImageSource =
                        new BitmapImage(
                        new Uri(@"Skin\" + _currentSkin + @"\Interface\Caps.png",
                                UriKind.Relative))
                };
                btn_Remote_Key_Caps.Background = imgCaps;
        	    btn_Remote_Key_A.Content = "a";
                btn_Remote_Key_B.Content = "b";
                btn_Remote_Key_C.Content = "c";
                btn_Remote_Key_D.Content = "d";
                btn_Remote_Key_E.Content = "e";
                btn_Remote_Key_F.Content = "f";
                btn_Remote_Key_G.Content = "g";
                btn_Remote_Key_H.Content = "h";
                btn_Remote_Key_I.Content = "i";
                btn_Remote_Key_J.Content = "j";
                btn_Remote_Key_K.Content = "k";
                btn_Remote_Key_L.Content = "l";
                btn_Remote_Key_M.Content = "m";
                btn_Remote_Key_N.Content = "n";
                btn_Remote_Key_O.Content = "o";
                btn_Remote_Key_P.Content = "p";
                btn_Remote_Key_Q.Content = "q";
                btn_Remote_Key_R.Content = "r";
                btn_Remote_Key_S.Content = "s";
                btn_Remote_Key_T.Content = "t";
                btn_Remote_Key_U.Content = "u";
                btn_Remote_Key_V.Content = "v";
                btn_Remote_Key_W.Content = "w";
                btn_Remote_Key_X.Content = "x";
                btn_Remote_Key_Y.Content = "y";
                btn_Remote_Key_Z.Content = "z";
        	}
            else
        	{
                var imgCaps = new ImageBrush
                {
                    ImageSource =
                        new BitmapImage(
                        new Uri(@"Skin\" + _currentSkin + @"\Interface\Caps_Selected.png",
                                UriKind.Relative))
                };
                btn_Remote_Key_Caps.Background = imgCaps;
                btn_Remote_Key_A.Content = "A";
                btn_Remote_Key_B.Content = "B";
                btn_Remote_Key_C.Content = "C";
                btn_Remote_Key_D.Content = "D";
                btn_Remote_Key_E.Content = "E";
                btn_Remote_Key_F.Content = "F";
                btn_Remote_Key_G.Content = "G";
                btn_Remote_Key_H.Content = "H";
                btn_Remote_Key_I.Content = "I";
                btn_Remote_Key_J.Content = "J";
                btn_Remote_Key_K.Content = "K";
                btn_Remote_Key_L.Content = "L";
                btn_Remote_Key_M.Content = "M";
                btn_Remote_Key_N.Content = "N";
                btn_Remote_Key_O.Content = "O";
                btn_Remote_Key_P.Content = "P";
                btn_Remote_Key_Q.Content = "Q";
                btn_Remote_Key_R.Content = "R";
                btn_Remote_Key_S.Content = "S";
                btn_Remote_Key_T.Content = "T";
                btn_Remote_Key_U.Content = "U";
                btn_Remote_Key_V.Content = "V";
                btn_Remote_Key_W.Content = "W";
                btn_Remote_Key_X.Content = "X";
                btn_Remote_Key_Y.Content = "Y";
                btn_Remote_Key_Z.Content = "Z";
        	}
            _keyShift = !_keyShift;
        }

        private void btn_Remote_Key_0_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.SendVirtKey('0');
        }

        private void btn_Remote_Key_1_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.SendVirtKey('1');
        }

        private void btn_Remote_Key_2_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.SendVirtKey('2');
        }

        private void btn_Remote_Key_3_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.SendVirtKey('3');
        }

        private void btn_Remote_Key_4_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.SendVirtKey('4');
        }

        private void btn_Remote_Key_5_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.SendVirtKey('5');
        }

        private void btn_Remote_Key_6_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.SendVirtKey('6');
        }

        private void btn_Remote_Key_7_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.SendVirtKey('7');
        }

        private void btn_Remote_Key_8_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.SendVirtKey('8');
        }

        private void btn_Remote_Key_9_Click(object sender, RoutedEventArgs e)
        {
            _xbmc.Controls.SendVirtKey('9');
        }

    }
}
